/**
 *
 */
package ua.at.tsvetkov.samizdat.activities;

import ua.at.tsvetkov.application.AppConfig;
import ua.at.tsvetkov.samizdat.Const;
import ua.at.tsvetkov.samizdat.Key;
import ua.at.tsvetkov.samizdat.R;
import ua.at.tsvetkov.samizdat.adapters.AdtAcBook;
import ua.at.tsvetkov.samizdat.adapters.AdtBookColors;
import ua.at.tsvetkov.samizdat.adapters.AdtBookTextSize;
import ua.at.tsvetkov.samizdat.data.AllBooksDownloader;
import ua.at.tsvetkov.samizdat.data.Book;
import ua.at.tsvetkov.samizdat.data.BookColor;
import ua.at.tsvetkov.samizdat.data.BookDownloader;
import ua.at.tsvetkov.samizdat.data.FavoriteAuthors;
import ua.at.tsvetkov.samizdat.data.FavoriteBooks;
import ua.at.tsvetkov.samizdat.data.OnCompleteLoadListener;
import ua.at.tsvetkov.samizdat.data.ReadedBooksData;
import ua.at.tsvetkov.ui.Rout;
import ua.at.tsvetkov.util.Log;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author A.Tsvetkov 2011, http://tsvetkov.at.ua, al@ukr.net
 */
public class AcBook extends AcTemplate {

	private static final int	MENU_BOOK_TEXT_SIZE			= 5;
	private static final int	MENU_DELETE						= 4;
	private static final int	MENU_BOOK_COLORS				= 3;
	private static final int	MENU_LOAD_ALL_AUTHR_BOOKS	= 2;
	private static final int	MENU_FAVORITES_AUTHORS		= 1;
	private static final int	MENU_FAVORITS					= 0;

	private static final int	DIALOG_COLOR_SELECT			= 1;

	private BookDownloader		bookDownloader;
	private FavoriteAuthors		favoriteAuthors;
	private FavoriteBooks		favoriteBooks;
	private ReadedBooksData		readedBooksData;
	private TextView				title;
	private TextView				author;
	private float					textSize;
	private Book					book;
	private String					authorUrl;
	private AdtAcBook				mAdapter;
	private AdtBookTextSize		adtBookTextSize;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		super.onCreate(savedInstanceState);
		ActivityManager activityManager = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);
		activityManager.killBackgroundProcesses("ua.at.tsvetkov.samizdat");
		System.gc();
		try {
			book = new Book(AppConfig.getString(Key.CURRENT_BOOK));
			Log.v(book.toString());
		} catch (Exception e) {
			Log.e(e);
			Toast.makeText(this, "Ошибка на сервере.\nНе могу получить данные по книге.", Toast.LENGTH_LONG);
			finish();
		}
		addListView();
		listView.setDividerHeight(0);
		System.gc();
		bookDownloader = new BookDownloader(this, book, (ProgressDialog) onCreateDialog(AcTemplate.DIALOG_LOAD));
		mAdapter = new AdtAcBook(AcBook.this, bookDownloader);
		listView.setAdapter(mAdapter);
		textInfo.setVisibility(View.VISIBLE);
		favoriteAuthors = new FavoriteAuthors(this);
		favoriteBooks = new FavoriteBooks(this);
		readedBooksData = new ReadedBooksData();
		textSize = AppConfig.getFloat(Key.TEXT_SIZE, Const.DEFAULT_TEXT_SIZE);
		author = (TextView) findViewById(R.id.AcTemplateTitle);
		author.setText(book.author);
		title = (TextView) findViewById(R.id.AcTemplateInfo);
		title.setText(book.title);
		// pages = (TextView) findViewById(R.id.AcTemplatePages);
		// pages.setText("0%");
	}

	private void loadSettings() {
		favoriteAuthors.load();
		favoriteBooks.load();
		readedBooksData.load();
		readedBooksData.getBookData(book);
		Log.v("After " + book);
	}

	private void saveSettings() {
		book.position = listView.getFirstVisiblePosition();
		readedBooksData.putBook(book);
		Log.v("Current " + book);
		readedBooksData.save();
		favoriteAuthors.save();
		favoriteBooks.save();
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.clear();
		menu.add(0, MENU_FAVORITS, 0, "Избранное").setIcon(R.drawable.ic_opt_favorite);
		menu.add(0, MENU_FAVORITES_AUTHORS, 0, "Избранные авторы").setIcon(R.drawable.ic_opt_favorite_author);
		menu.add(0, MENU_BOOK_COLORS, 0, "Цвет текста").setIcon(R.drawable.ic_opt_text_colors);
		menu.add(0, MENU_BOOK_TEXT_SIZE, 0, "Размер текста").setIcon(R.drawable.ic_opt_text_colors);
		menu.add(0, MENU_LOAD_ALL_AUTHR_BOOKS, 0, "Загрузить книги автора").setIcon(R.drawable.ic_opt_load);
		menu.add(0, MENU_DELETE, 0, "Удалить").setIcon(android.R.drawable.ic_delete);
		return super.onCreateOptionsMenu(menu);
	}

	/*
	 * (non-Javadoc)
	 * @see ua.at.tsvetkov.debug.AcSimpleTrackingActivity#onPause()
	 */
	@Override
	protected void onPause() {
		saveSettings();
		super.onPause();
	}

	/* (non-Javadoc)
	 * @see ua.at.tsvetkov.debug.AcSimpleTrackingActivity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		bookDownloader.clear();
		bookDownloader = null;
		System.gc();
		super.onStop();
	}

	/*
	 * (non-Javadoc)
	 * @see ua.at.tsvetkov.debug.AcSimpleTrackingActivity#onResume()
	 */
	@Override
	protected void onResume() {
		loadSettings();
		loadBook();
		super.onResume();
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		int action = event.getAction();
		int keyCode = event.getKeyCode();
		switch (keyCode) {
			case KeyEvent.KEYCODE_VOLUME_UP:
				if (action == KeyEvent.ACTION_DOWN) {
					paging(false);
				}
				return true;
			case KeyEvent.KEYCODE_VOLUME_DOWN:
				if (action == KeyEvent.ACTION_DOWN) {
					paging(true);
				}
				return true;
			default:
				return super.dispatchKeyEvent(event);
		}
	}

	/**
	 * Листание страниц
	 * 
	 * @param next true - вперед false - назад
	 */
	private void paging(final boolean next) {
		int pos = listView.getFirstVisiblePosition();
		int count = 1;
		if (next) {
			listView.setSelection(pos + count);
		} else {
			listView.setSelection(pos - count);
		}
	}

	private void loadBook() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				bookDownloader.download(true, false);
				authorUrl = bookDownloader.getAuthorUrl();
				mAdapter.update();
				updateBookPosition();
			}

		}).start();
	}

	protected void updateBookPosition() {
		listView.post(new Runnable() {

			@Override
			public void run() {
				listView.setSelection(book.position);
				listView.getHeight();
			}
		});
	}

	/**
	 * Options menu handler
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case MENU_FAVORITS: {
				favoriteBooks.setFavorite(book);
				break;
			}
			case MENU_FAVORITES_AUTHORS: {
				favoriteAuthors.setFavoriteAuthor(book);
				break;
			}
			case MENU_LOAD_ALL_AUTHR_BOOKS: {
				loadAllAuthorBooks();
				break;
			}
			case MENU_BOOK_COLORS: {
				showDialog(DIALOG_COLOR_SELECT);
				break;
			}
			case MENU_BOOK_TEXT_SIZE: {
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle("Выбор размера текста");
				adtBookTextSize = new AdtBookTextSize(this);
				builder.setAdapter(adtBookTextSize, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, final int position) {
						textSize = (Float) adtBookTextSize.getItem(position);
						mAdapter.setTextSize(textSize);
						AppConfig.putSetting(Key.TEXT_SIZE, textSize, AppConfig.SAVE);
					}

				});
				builder.create().show();
				break;
			}
			case MENU_DELETE: {
				book.delete();
				AppConfig.putSetting(Key.CURRENT_BOOK, "");
				finish();
				break;
			}
		}
		return false;
	}

	/**
	 * Загрузить все книги данного автора
	 */
	private void loadAllAuthorBooks() {
		AllBooksDownloader allBooksDownloader = new AllBooksDownloader(this, (ProgressDialog) onCreateDialog(DIALOG_LOAD), authorUrl);
		allBooksDownloader.setOnCompleteLoadListener(new OnCompleteLoadListener() {

			@Override
			public void loadComplete(boolean isLoaded) {
				if (isLoaded) {
					Rout.toast(AcBook.this, "Загрузка книг автора завершена успешно.", Toast.LENGTH_LONG);
				} else {
					Rout.toast(AcBook.this, "Загрузка книг автора завершена с ошибками.", Toast.LENGTH_LONG);
				}
			}

		});
		allBooksDownloader.download();
	}

	/*
	 * (non-Javadoc)
	 * @see ua.at.tsvetkov.samizdat.activities.AcTemplate#onCreateDialog(int)
	 */
	@Override
	public Dialog onCreateDialog(int id) {
		switch (id) {
			case DIALOG_COLOR_SELECT: {
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle("Выбор цветов для чтения");
				AdtBookColors adt = new AdtBookColors(this);
				builder.setAdapter(adt, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, final int position) {
						mAdapter.setBookColor(BookColor.colors[position]);
						AppConfig.putSetting(Key.BOOK_COLORS_SET, position, AppConfig.SAVE);
					}

				});
				return builder.create();
			}
		}
		return super.onCreateDialog(id);
	}

}
